import { mapMutations } from 'vuex'

let ws = null

let app = {
  ...mapMutations(['setAlarms'])
}

export default class socketTool {
  static init() {
    if (ws == null) {
      try {
        window.rootVue.setAlarms = app.setAlarms
        ws = new WebSocket(window.global.config.socketUrl + 'Home/CreateSocket')

        ws.onopen = function() {
          console.log('WebSocket连接成功！')
        }
        ws.onmessage = function(res) {
          console.log('推送数据：' + res.data)
          window.rootVue.setAlarms()
        }
        ws.onerror = function(error) {
          console.log('WebSocket连接失败,错误:' + error)
        }
        ws.onclose = function() {
          console.log('WebSocket连接关闭！')
        }
      } catch (e) {
        console.warn(e)
      }
    }
  }

  // 发送数据到后端
  static send(msg) {
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(msg)
    } else {
      console.warn('WebSocket连接已关闭！')
    }
  }

  // 关闭Socket
  static close() {
    ws.close()
  }
}
